#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      Sanchez
#
# Created:     26/06/2012
# Copyright:   (c) Sanchez 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import sys
from PyQt4 import QtGui, QtCore
from Ui_MainForm import Ui_MainWindow
from moddt8837 import  *
import pylab as plt
import scipy as sc
from scipy.io.matlab import mio
from datetime import date
import  os
import string

def ParseScanRecord(buf):
    scanCount=buf[0]
    numChannel=buf[1]
    scanIndex=buf[2]
    ChannelValues=buf[5:]
    return scanCount, numChannel, scanIndex, ChannelValues

def GetScanRecord(h, index, numScan):
    if numScan>0:
        sFetch=":AD:FETCH? "+str(index) +","+str(numScan)+"\n"
    else:
        sFetch=":AD:FETCH? "+str(index) +"\n"
    w.ListInfo.addItem(sFetch)        
    h.write(sFetch)
    w.data=h.read_raw()
    # read first 2 chars of returned IEE block data
    s=struct.unpack_from('2c',w.data)
    print "s=",s, len(s)
    if len(s)!=2:
        w.ListInfo.addItem("receive "+str(len(s))+" bytes")
    if s[0]!="#":  # The first char should be # 
        w.ListInfo.addItem("Invalid first char...")        
#        The second char a single non-zero decimal number denoting the 
#        of the number of decimal numbers that follow        
    numCharLen=int(s[1])  # en general 6 mais atention parfois 2
    if numCharLen!=6:
        w.ListInfo.addItem("receive "+str(numCharLen)+" bytes")
    else:
        # lecture taille du bloc de data suivant
        fmt=str(numCharLen)+"c"    #formattage header
        s=struct.unpack_from(fmt,w.data[2:])
        print "s unpack =",s
    #    Find the length of the binary block of data that follows the
    #    characters parsed thus far    
        L=len(s)
        lenRecord=0
        for i in range(L):
            lenRecord = pow(10,i)*int(s[L-i-1]) + lenRecord
        print "Length record =",lenRecord    
#        Read the entire binary block of data    
        fmt=">"+str(lenRecord/4)+"l"
        buf=struct.unpack_from(fmt,w.data[8:])  # tout le buffer
        w.scanCount, w.numChannel, w.scanIndex, w.ChannelValues=ParseScanRecord(buf)
    return 
    
    
# creation de la classe acqui en derivant QThread
class Acqui(QtCore.QThread):
    "initialisation u thread affichage"
    def __init__(self):
        "initialisation du thread"
        QtCore.QThread.__init__(self)  # initialisation du thread

    def run(self):
        "programme principal du thread, excecution"
        w.ListInfo.addItem("okkkkkkkkk")
#        w.finish = False
#        w.savedone1=0
#        w.savedone2=1
#        w.i0=0
        w.index=0
        while (~w.finish):
            w.indexStart, w.indexEnd=0, 0
            w.ADstatus, w.indexStart, w.indexEnd=GetAdBufferStatus(w.h1)
##            w.listinfo.addItem("info "+str(w.ADstatus)+" "+str(w.ideb % 524032)+" "+str(w.ifin % 524032))
            w.ListInfo.addItem("info "+str(w.ADstatus)+" "+str(w.indexStart)+" "+str(w.indexEnd))
            GetScanRecord(w.h1, w.index, -1)
            print w.scanCount, w.numChannel, w.scanIndex
            w.ListInfo.scrollToBottom()
            time.sleep(1)
            w.index=w.scanIndex + w.scanCount
        w.finish=True

class MonAppli(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        # Configure l'interface utilisateur.
        self.setupUi(self)
        self.DEV1 = "TCPIP::169.254.241.19::INSTR"
        self.h1=0 #handle carte
        self.level=1 # level  1 (1/10V) input
        self.fs=5000 # sampling rate
        self.dt = 1.0/self.fs # period
        self.acqtime=2  #duree 2s
        self.data = []
        self.data = []
        self.sizeHeader =0
        self.sizeBuffer=0
        self.header=[]
        self.v=[]
        self.tab_coupling=["AC","DC"]
        self.finish = True
        self.scanIndex=0
        self.scanCount=0
        self.numChannel=0
        self.scanIndex=0
        self.ChannelValues=[]
  
#--------------------------------------------------------------------
# menus
#--------------------------------------------------------------------
  
#--------------------------------------------------------------------
# boutons
#--------------------------------------------------------------------
        self.connect(self.pushButtonStart,QtCore.SIGNAL("clicked()"),On_pushButtonStart)
        self.connect(self.pushButtonStop,QtCore.SIGNAL("clicked()"),On_pushButtonStop)
  
  
#--------------------------------------------------------------------
# lineEdit
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# fonctions des menus 
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# fonctions des boutons   
#--------------------------------------------------------------------
def On_pushButtonStart():
    print "pushButtonStart"
    w.data = []
    w.data = []
    w.sizeHeader =0
    w.sizeBuffer=0
    w.header=[]
    w.v=[]
    # modification du nom de projet
    w.projectName = "data" # str(w.ProjectName.text()).rstrip()
    w.ListInfo.addItem("Project name : "+w.projectName)
    w.ListInfo.scrollToBottom()
    # modification du nom des fichiers"
    w.fileName = "demo" # str(w.FileName.text()).rstrip()
    w.ListInfo.addItem("Filename name : "+w.fileName)
    w.ListInfo.scrollToBottom()
# creation dossier donnees
    racine=os.getcwd()  # garde la racine
    today = date.today() # date du jour
    s=today.strftime("%Y%m%d") # conversion aaaammjj
    w.path = os.path.join(racine,w.projectName,s)+os.sep
    if not os.path.exists(w.path):
        os.makedirs(w.path, mode=644)
        w.ListInfo.addItem(w.path)
        w.ListInfo.scrollToBottom()
        
        
    w.h1 = getHandle(w.DEV1)
    mess=getID(w.h1)
    w.ListInfo.addItem("Device name : "+mess)
    w.ListInfo.addItem(" Enable AD for all channel")
    doRST(w.h1)
    err1 = setAdEnableAll(w.h1)
    w.ListInfo.addItem("Channel coupling AC ...")
    w.coupling="AC"
    err1 = setCouplage(w.h1,'DC')
    w.ListInfo.addItem("Init level ...")
    w.level=1   # 1V en entree 1 ou 10
    err1 = setGain(w.h1,w.level)
    w.ListInfo.addItem("Mode  buffer wrap/no wrap ...")
    err1 = setWrap(w.h1,"on")  #   buffer circulaire off
    w.h1.write("ad:buffer:size?")
    mess = w.h1.read()
    w.ListInfo.addItem("Buffer size : "+mess)
    w.ListInfo.addItem("Initialisation horloge interne ...")
    err1=setADClockInternal(w.h1)
    w.ListInfo.addItem("Initialisation frequence horloge interne ...")
    w.fs=5000 # int(w.SampleRate.text()) # lecture freq ech Hz
    err1=setFreqClock(w.h1,w.fs)
    w.dt=1.0/w.fs    #periode echantillonnange
    w.ListInfo.addItem("Sampling rate : "+str(w.fs)+" hz")
    w.ListInfo.addItem("Init source trigger immediat ...")
    err1=setAdTrigSourceImm(w.h1)
    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("avant armement "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.addItem( "Armement des mesures, pret a lancer ...")
    err1=setAdArm(w.h1)
    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("apres armement "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.addItem("lance la mesure ....")
    err1=setAdInit(w.h1)
    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("mesure lancee "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.scrollToBottom()

    w.tacq= 20 # int(w.acqTime.text()) # lecture duree acquisition


    w.buffersize=w.tacq/w.dt # nombre d echantillon pour tacq


    N=200 #254  # work well only with 100 !!!!!!!!!!!!!!!!! or less than 255 (254)


    w.nbblock=int(w.buffersize/N-1)
    w.ListInfo.addItem("attente .....")
    ThreadAcq.start()


    return
  
def On_pushButtonStop():
    print "pushButtonStop"
    w.finish = False
    err1=setAdStop(w.h1)
    ThreadAcq.terminate()
    w.ListInfo.addItem("fin acquisition .....")
    doRST(w.h1)
    return
  
#--------------------------------------------------------------------
# fonctions des LineEdit    
#--------------------------------------------------------------------
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MonAppli()
    ThreadAcq = Acqui()
    w.show()
    sys.exit(app.exec_())
